<template>
  <div class="quick-test">
    <h3>🚀 快速数据测试</h3>
    <p>点击按钮测试API数据格式并自动修复问题</p>
    
    <div class="test-controls">
      <button @click="quickTest" :disabled="testing" class="primary-btn">
        {{ testing ? '测试中...' : '🔍 快速测试并修复' }}
      </button>
      <button @click="clearResults" class="secondary-btn">
        清除结果
      </button>
    </div>
    
    <div v-if="result" class="result-section">
      <div :class="['result-status', result.success ? 'success' : 'error']">
        <h4>{{ result.success ? '✅ 测试成功' : '❌ 测试失败' }}</h4>
        <p>{{ result.message }}</p>
      </div>
      
      <div v-if="result.analysis" class="analysis">
        <h4>📊 数据分析结果</h4>
        <div class="analysis-grid">
          <div class="analysis-item">
            <strong>数据类型:</strong> {{ result.analysis.dataType }}
          </div>
          <div class="analysis-item">
            <strong>数据长度:</strong> {{ result.analysis.length }}
          </div>
          <div class="analysis-item">
            <strong>第一项字段:</strong> {{ result.analysis.fields.join(', ') }}
          </div>
        </div>
        
        <div v-if="result.analysis.sample" class="sample-data">
          <h5>数据样本:</h5>
          <pre>{{ JSON.stringify(result.analysis.sample, null, 2) }}</pre>
        </div>
      </div>
      
      <div v-if="result.suggestions.length > 0" class="suggestions">
        <h4>💡 修复建议</h4>
        <ul>
          <li v-for="suggestion in result.suggestions" :key="suggestion">
            {{ suggestion }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

interface TestResult {
  success: boolean
  message: string
  analysis?: {
    dataType: string
    length: number | string
    fields: string[]
    sample?: any
  }
  suggestions: string[]
}

const testing = ref(false)
const result = ref<TestResult | null>(null)

async function quickTest() {
  testing.value = true
  result.value = null
  
  try {
    console.log('开始快速测试...')
    
    // 测试代理请求
    const response = await fetch('/api/jsondata/newAreaCodeV2024.json')
    
    if (!response.ok) {
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    }
    
    const rawData = await response.json()
    console.log('原始数据:', rawData)
    
    // 分析数据结构
    const analysis = analyzeData(rawData)
    const suggestions = generateSuggestions(analysis, rawData)
    
    result.value = {
      success: true,
      message: '数据获取成功！已分析数据结构。',
      analysis,
      suggestions
    }
    
    // 如果有修复建议，显示如何应用
    if (suggestions.length > 0) {
      console.log('检测到数据格式问题，建议:', suggestions)
    }
    
  } catch (error) {
    console.error('快速测试失败:', error)
    
    result.value = {
      success: false,
      message: `测试失败: ${error instanceof Error ? error.message : String(error)}`,
      suggestions: [
        '检查网络连接',
        '确保开发服务器正在运行',
        '检查Vite代理配置',
        '尝试使用调试面板的其他测试方法'
      ]
    }
  } finally {
    testing.value = false
  }
}

function analyzeData(data: any) {
  let targetData = data
  let dataType = 'unknown'
  let length: number | string = 'N/A'
  let fields: string[] = []
  let sample: any = null
  
  if (Array.isArray(data)) {
    dataType = 'array'
    length = data.length
    targetData = data
    if (data.length > 0) {
      fields = Object.keys(data[0])
      sample = data[0]
    }
  } else if (data && typeof data === 'object') {
    if (data.data && Array.isArray(data.data)) {
      dataType = 'object-with-data-array'
      length = data.data.length
      targetData = data.data
      if (data.data.length > 0) {
        fields = Object.keys(data.data[0])
        sample = data.data[0]
      }
    } else {
      dataType = 'object'
      fields = Object.keys(data)
      sample = data
    }
  }
  
  return {
    dataType,
    length,
    fields,
    sample
  }
}

function generateSuggestions(analysis: any, rawData: any): string[] {
  const suggestions: string[] = []
  
  if (analysis.fields.length === 0) {
    suggestions.push('数据为空或格式不正确')
    return suggestions
  }
  
  // 检查必需字段
  const hasId = analysis.fields.includes('id') || analysis.fields.includes('code') || analysis.fields.includes('value') || analysis.fields.includes('areaCode')
  const hasName = analysis.fields.includes('name') || analysis.fields.includes('label') || analysis.fields.includes('title') || analysis.fields.includes('areaName')
  
  if (!hasId) {
    suggestions.push('缺少ID字段，需要id、code、value或areaCode字段之一')
  }
  
  if (!hasName) {
    suggestions.push('缺少名称字段，需要name、label、title或areaName字段之一')
  }
  
  // 检查数据结构
  if (analysis.dataType === 'object' && !rawData.data) {
    suggestions.push('数据是对象但没有data字段，可能需要调整数据解析逻辑')
  }
  
  if (analysis.length === 0) {
    suggestions.push('数据数组为空')
  }
  
  if (suggestions.length === 0) {
    suggestions.push('数据格式看起来正常，如果仍有问题可能是字段映射问题')
  }
  
  return suggestions
}

function clearResults() {
  result.value = null
}
</script>

<style scoped>
.quick-test {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  padding: 24px;
  margin: 20px 0;
}

.quick-test h3 {
  margin: 0 0 8px 0;
  font-size: 20px;
}

.quick-test p {
  margin: 0 0 20px 0;
  opacity: 0.9;
}

.test-controls {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.primary-btn, .secondary-btn {
  padding: 12px 24px;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.primary-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.primary-btn:hover:not(:disabled) {
  background-color: rgba(255, 255, 255, 0.3);
  transform: translateY(-1px);
}

.primary-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.secondary-btn {
  background-color: transparent;
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.secondary-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.result-section {
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 16px;
  margin-top: 16px;
}

.result-status {
  margin-bottom: 16px;
}

.result-status h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
}

.result-status p {
  margin: 0;
  opacity: 0.9;
}

.success h4 {
  color: #4ade80;
}

.error h4 {
  color: #f87171;
}

.analysis {
  margin-bottom: 16px;
}

.analysis h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #e2e8f0;
}

.analysis-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 8px;
  margin-bottom: 12px;
}

.analysis-item {
  background-color: rgba(255, 255, 255, 0.1);
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 12px;
}

.sample-data {
  margin-top: 12px;
}

.sample-data h5 {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #e2e8f0;
}

.sample-data pre {
  background-color: rgba(0, 0, 0, 0.3);
  padding: 12px;
  border-radius: 4px;
  font-size: 10px;
  overflow-x: auto;
  margin: 0;
}

.suggestions {
  margin-top: 16px;
}

.suggestions h4 {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #fbbf24;
}

.suggestions ul {
  margin: 0;
  padding-left: 20px;
}

.suggestions li {
  margin-bottom: 4px;
  font-size: 12px;
  opacity: 0.9;
}

@media (max-width: 768px) {
  .test-controls {
    flex-direction: column;
  }
  
  .analysis-grid {
    grid-template-columns: 1fr;
  }
}
</style>